package org.osll.tictactoe.transport.corba.client;

import java.io.IOException;

import org.omg.CORBA.ORB;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.CosNaming.NamingContextPackage.CannotProceed;
import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.osll.tictactoe.Control;
import org.osll.tictactoe.Team;
import org.osll.tictactoe.transport.corba.Adapter;
import org.osll.tictactoe.transport.corba.service.ServerConnection;
import org.osll.tictactoe.transport.corba.service.ServerConnectionHelper;

public class ServerConnectionImpl implements org.osll.tictactoe.ServerConnection {

	private ServerConnection service = null;
	
	public ServerConnectionImpl() {
		String args[] = new String[5];
		args[0] = "";
		args[1] = "-ORBInitialPort";
		args[2] = "1050";
		args[3] = "-ORBInitialHost";
		args[4] = org.osll.tictactoe.transport.DefaultOptions.getInstance().getHost();

	    // create and initialize the ORB
	    ORB orb = ORB.init(args, null);

	    // get the root naming context
	    org.omg.CORBA.Object objRef = null;
		try {
			objRef = orb.resolve_initial_references("NameService");
		} catch (InvalidName e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		  
	    // Use NamingContextExt instead of NamingContext. This is 
	    // part of the Interoperable naming Service.  
	    NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
	 
	    // resolve the Object Reference in Naming
	    String name = "TicTacToeLoginServer";
	    try {
			service = ServerConnectionHelper.narrow(ncRef.resolve_str(name));
		} catch (NotFound e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (CannotProceed e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (org.omg.CosNaming.NamingContextPackage.InvalidName e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	synchronized public Control connect(String name, Team team) {
		return new ControlImpl(service.connect(name, Adapter.convertTeam(team)),name,team);
	}

}
